/**
 * 通知管理器
 */
const EventEmitter = require('events');
const logger = require('./logger');
const axios = require('axios');
const config = require('./config');
const clientIdManager = require('./clientId');

class NotificationManager extends EventEmitter {
  constructor() {
    super();
    this.notifications = []; // 本地通知缓存
    this.unreadCount = 0;
  }

  /**
   * 添加通知
   */
  addNotification(notification) {
    const notificationId = notification.id || Date.now();
    
    // 检查通知是否已存在，避免重复添加
    const existingNotif = this.notifications.find(n => n.id === notificationId);
    if (existingNotif) {
      logger.warn(`⚠️ 通知已存在，跳过添加: ${notification.title} (ID: ${notificationId})`);
      return existingNotif;
    }
    
    const notif = {
      id: notificationId,
      title: notification.title,
      content: notification.content,
      type: notification.type || 'text', // text, image, both
      imageUrl: notification.imageUrl || notification.image_url || null,
      priority: notification.priority || 'normal', // low, normal, high, urgent
      targetType: notification.targetType || notification.target_type,
      senderId: notification.senderId || notification.sender_id,
      senderName: notification.senderName || notification.sender_name || 'System',
      isRead: false, // 新收到的通知默认未读
      createdAt: notification.createdAt || notification.created_at || new Date(),
      readAt: null
    };

    this.notifications.unshift(notif);
    this.unreadCount++;

    this.emit('notification-added', notif);
    logger.info(`📬 新通知: ${notif.title} (优先级: ${notif.priority})`);

    return notif;
  }

  /**
   * 标记通知为已读
   */
  async markAsRead(notificationId, isRead = true) {
    const notification = this.notifications.find(n => n.id === notificationId);
    if (notification) {
      // 本地更新
      const wasUnread = !notification.isRead;
      notification.isRead = isRead;
      notification.readAt = isRead ? new Date() : null;
      
      if (wasUnread && isRead) {
        this.unreadCount = Math.max(0, this.unreadCount - 1);
      } else if (!wasUnread && !isRead) {
        this.unreadCount++;
      }

      // 同步到服务器
      try {
        const serverUrl = config.getServerUrl();
        const userConfig = config.getUserConfig();
        const clientId = clientIdManager.getClientId();
        
        await axios.post(
          `${serverUrl}/api/notifications/${notificationId}/mark`,
          { isRead, clientId },
          {
            headers: {
              'Authorization': `Bearer ${userConfig.token}`
            }
          }
        );
        
        logger.info(`📖 通知已${isRead ? '标为已读' : '标为稍后再读'}: ${notification.title}`);
      } catch (error) {
        logger.error('同步通知状态失败:', error.message);
      }

      this.emit('notification-read', notification);
    }
  }

  /**
   * 标记所有通知为已读
   */
  markAllAsRead() {
    let count = 0;
    for (const notification of this.notifications) {
      if (!notification.isRead) {
        notification.isRead = true;
        notification.readAt = new Date();
        count++;
      }
    }
    this.unreadCount = 0;
    this.emit('all-notifications-read', count);
    logger.info(`[通知] 已将 ${count} 个通知标记为已读`);
  }

  /**
   * 删除通知
   */
  deleteNotification(notificationId) {
    const index = this.notifications.findIndex(n => n.id === notificationId);
    if (index !== -1) {
      const notification = this.notifications[index];
      if (!notification.isRead) {
        this.unreadCount = Math.max(0, this.unreadCount - 1);
      }
      this.notifications.splice(index, 1);
      this.emit('notification-deleted', notificationId);
      logger.info(`[通知] 已删除: ${notification.title}`);
    }
  }

  /**
   * 清除所有已读通知
   */
  clearRead() {
    const beforeCount = this.notifications.length;
    this.notifications = this.notifications.filter(n => !n.isRead);
    const removed = beforeCount - this.notifications.length;
    
    if (removed > 0) {
      this.emit('read-notifications-cleared', removed);
      logger.info(`[通知] 已清除 ${removed} 个已读通知`);
    }
  }

  /**
   * 获取所有通知
   */
  getNotifications() {
    return this.notifications;
  }

  /**
   * 获取未读通知
   */
  getUnreadNotifications() {
    return this.notifications.filter(n => !n.isRead);
  }

  /**
   * 获取未读数量
   */
  getUnreadCount() {
    return this.unreadCount;
  }

  /**
   * 清空所有通知
   */
  clear() {
    this.notifications = [];
    this.unreadCount = 0;
    this.emit('notifications-cleared');
    logger.info('[通知] 已清空所有通知');
  }

  /**
   * 从服务器加载通知列表
   */
  async loadFromServer() {
    try {
      const serverUrl = config.getServerUrl();
      const userConfig = config.getUserConfig();
      const clientId = clientIdManager.getClientId();

      const response = await axios.get(`${serverUrl}/api/notifications`, {
        params: {
          page: 1,
          pageSize: 50,
          clientId
        },
        headers: {
          'Authorization': `Bearer ${userConfig.token}`
        }
      });

      if (response.data.success) {
        const notifications = response.data.data.notifications;
        
        // 清空本地缓存
        this.notifications = [];
        this.unreadCount = 0;

        // 添加通知（不触发notification-added事件）
        for (const notif of notifications) {
          const notification = {
            id: notif.id,
            title: notif.title,
            content: notif.content,
            type: notif.type,
            imageUrl: notif.image_url,
            priority: notif.priority,
            targetType: notif.target_type,
            senderId: notif.sender_id,
            senderName: notif.sender_name,
            isRead: notif.is_read,
            createdAt: notif.created_at,
            readAt: notif.read_at
          };

          this.notifications.push(notification);
          if (!notification.isRead) {
            this.unreadCount++;
          }
        }

        logger.info(`📥 已从服务器加载 ${notifications.length} 条通知，未读: ${this.unreadCount}`);
        this.emit('notifications-loaded', this.notifications);
        return this.notifications;
      }
    } catch (error) {
      logger.error('加载通知列表失败:', error.message);
      return [];
    }
  }

  /**
   * 获取未读数量（从服务器）
   */
  async getUnreadCountFromServer() {
    try {
      const serverUrl = config.getServerUrl();
      const userConfig = config.getUserConfig();
      const clientId = clientIdManager.getClientId();

      const response = await axios.get(`${serverUrl}/api/notifications/unread/count`, {
        params: { clientId },
        headers: {
          'Authorization': `Bearer ${userConfig.token}`
        }
      });

      if (response.data.success) {
        return response.data.data.count;
      }
      return 0;
    } catch (error) {
      logger.error('获取未读数量失败:', error.message);
      return this.unreadCount;
    }
  }
}

module.exports = new NotificationManager();
